package ginmiddleware

import (
	"gin-xorm/app"
	"gin-xorm/database"
	"gin-xorm/log"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type MLog struct {
	log.Log
}

var mLog MLog

func init() {
	mLog.Tag = "middleware"
}

// ErrorHandler is a middleware to handle errors encountered during requests
func ErrorHandler(c *gin.Context) {
	c.Next()
	if len(c.Errors) > 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"errors": c.Errors,
		})
	}
}

// NoRoute is a middleware to handle page not found during requests
func NoRoute(c *gin.Context) {
	c.HTML(http.StatusNotFound, "404.html", gin.H{})
}

func RequestTime(c *gin.Context) {
	start := time.Now()
	c.Next()
	since := time.Since(start)
	mLog.Info("request time", since)
}

// Auth 获取token，并验证是否有效
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenstring := c.GetHeader("Authorization")
		if tokenstring == "" || !strings.HasPrefix(tokenstring, "Bearer") {
			c.JSONP(400, app.Response{
				Code: 400,
				Msg:  "token无效",
			})
			c.Abort()
			return
		}
		tokenstring = tokenstring[7:]
		token, claims, err := database.ParseToken(tokenstring)
		if err != nil || !token.Valid {
			c.JSONP(200, app.Response{
				Code: 400,
				Msg:  "token无效",
			})
			c.Abort()
			return
		}

		c.Set("userid", claims.UserId)
		c.Next()
	}

}
